<template>
  <header class="common-app-header">
    <left-btn :btn="option.leftBtn" :page="option.page" @click="_back()"></left-btn>
    <div class="common-app-title" :style="{'right':getTitleRight() + 'px'}"><div>{{option.title}}</div></div>
    <div class="common-app-right-btns">
      <right-btn v-for="(item, index) in option.operations" :key="item" :btn="item" :page="option.page"  :shareurl="option.shareurl"></right-btn>
      <div v-if="showHead" class="common-app-btn-header" @click="selfDetail"><img :src="userHead"></div>
    </div>
  </header>
</template>

<script>
  import Vue from 'vue'
  import router from 'router/index.js'
  import RemoteDAO from 'common/remoteDAO'
  import LocalDAO from 'common/localDAO'
  import Constant from 'common/constant'
  import _ from 'underscore'

  export default {
    data(){
      return{
        userHead:LocalDAO.getUserHead(),
        showHead:false
      }
    },
    props: {
      option: {
        type: Object
      }
      /**
       * 示例：
       * option = headerOption: {
          title: '牛人牛股',
          leftBtn: Constant.leftBtn.CLOSE,
          operations: [Constant.operation.SEARCH，Constant.operation.REFRESH]
          page:Constant.page.******* // 有分享时 或  index//有头像时 可选
          shareurl: "" //可选  分享老何复盘、精选牛股时
        }
       */
    },
    created: function () {
      if(LocalDAO.getNickname() && _.indexOf([Constant.menu.ROCKMAN,Constant.menu.ROCKMAN,Constant.menu.GAME],this.option.page)>-1){
        this.showHead = true;
      }
      //绑定最牛股票和最牛组合切换时，右上的显隐创建组合按钮
      this.$root.eventHub.$on('groupbox.active', ()=> {
        this.option.operations.push(Constant.operation.BUILD_GROUP)
      });
      this.$root.eventHub.$on('stockbox.active', ()=> {
        this.option.operations = _.without(this.option.operations,Constant.operation.BUILD_GROUP);
      });
    },
    methods:{
      selfDetail(){
        this.$router.push({path:'/selfdetail'})
      },
      getTitleRight(){
        let num = this.option.operations.length;
        let titleRight = 56;
        if(num>0){
          if(this.showHead){
            num++
          }
          titleRight = num*46+10
        }
        return titleRight
      }
    }
  }

  // 左侧按钮
  Vue.component('left-btn', {
    data () {
      return {class: 'common-app-btn-back', iconclass: 'iconfont icon-fanhui'}
    },
    props: {
      btn: {type: String},
      page: {type:String}
    },
    render: function (createElement) {
      var self = this
      if (self.btn === Constant.leftBtn.CLOSE) {
        self.class = 'common-app-btn-close'
        self.iconclass = 'iconfont icon-x'
      }
      return createElement(
        'div',
        {
          attrs: {
            class: self.class
          },
          on: {
            click: function () {
              if(self.btn ==  Constant.leftBtn.CLOSE || typeof (self.$route.query.cleanStorage)!== 'undefined'){
                window.location.href = 'gtjanormal://goback'
              }else if(self.page == Constant.page.BULID_GROUP_SUCC){ //创建组合成功后的页面按返回调到创建组合之前的页面
                router.go(-4)
              }else if(self.page == Constant.page.LEARN_GROUP_SUCC){//偷师组合成功后的页面按返回调到创建组合之前的页面
                router.go(-2)
              }else{
                router.go(-1)
              }
            }
          }
        },
        [
          createElement('i', {
            attrs: {
              class: self.iconclass
            }
          })
        ]
      )
    }
  })

  // 右侧按钮
  Vue.component('right-btn', {
    data () {
      return {class: '', iconclass: '', clickMethod: function(){}} //按钮类名，icon图标类名，点击按钮的方法
    },
    props: {
      btn: {type: String},
      page: {type: String},
      isLogin :{type: Boolean},
      shareurl:{type:String}
    },
    methods:{
      search(){
        this.$router.push('/search/search');
        var kv = {"usercode": LocalDAO.getUserCode(), "k2": ""};
        TDAPP.onEvent("19001", "", kv);
        TDAPP.send();
      },
      searchInBuildGroup(){
        this.$router.push('/buildgroup/searchstock')
      },
      refresh(){
        window.location.reload();
        if (this.page == Constant.storage.SHARE_OTHER_DETAILS) {
          var kv = {"usercode": LocalDAO.getUserCode(), "k2": ""};
          TDAPP.onEvent("15017", "", kv);
          TDAPP.send();
        }
      },
      buildGroup(){
        var self = this;
        if (LocalDAO.getNickname()) {
          self.$router.push({path:'/buildgroup/buildstep1'})
        } else {
          var kv = {"usercode": "", "k2": ""};
          TDAPP.onEvent("2014", "", kv);
          TDAPP.send();
          RemoteDAO.callNativeLogin(function (response) {
            if (response.error == 0) {
              self.$router.push({path:'/buildgroup/buildstep1'})
            } else {
              self.$store.dispatch('setTip',{text: response.data});
            }
          });
        }
      },
      buildGame(){
        var self = this;
        var nickName = LocalDAO.getNickname();
        if(nickName == undefined || nickName == null || nickName.length <= 0){
          var kv = {"usercode":LocalDAO.getUserCode()};
          TDAPP.onEvent('2006',"",kv);
          TDAPP.send();
          RemoteDAO.callNativeLogin(function (response) {
            var userCode =  LocalDAO.getUserCode();
            if(typeof (userCode) !== 'undefined' && userCode !== null && userCode.length > 0){
              self.$router.push({path:'/game/buildgame'});
            }
          })
        }else{
          var userCode =  LocalDAO.getUserCode();
          if(typeof (userCode) !== 'undefined' && userCode !== null && userCode.length > 0){
            self.$router.push({path:'/game/buildgame'});
          }else{
            self.$store.dispatch('setTip',{text:"发生异常userCode="+userCode});
          }
        }
        var kv = {"usercode":LocalDAO.getUserCode()};
        TDAPP.onEvent('8003',"",kv);
        TDAPP.send();
      },
      selfDetail(){
        this.$router.push({path:'/selfdetail'})
      },
      gameRule(){
        this.$router.push({path:'/game/rules'});
      },
      hugeGameRule(){
        this.$router.push({path:'/game/rules', query: { kind: 'CLS'}});
      },
      jysGameRule(){
        this.$router.push({path:'/game/rules', query: { kind: 'JYS'}});
      },
      tutorial(){
        this.$router.push({path:'/tutorial'});
        var kv = {"usercode": LocalDAO.getUserCode(), "k2": ""};
        TDAPP.onEvent("15015", "", kv);
        TDAPP.send();
      },
      quest(){
        if(this.page == Constant.page.FUND_BUY){
          this.$root.eventHub.$emit('showFundQuest')
        }else if(this.page == Constant.page.SELF_ACCOUNT){

        }
      },
      share(){
        var nickname = LocalDAO.getNickname();
        var usercode = LocalDAO.getUserCode();
        var self = this;
        var tdId = "";
        var title = "牛人牛股";
        var content = "";
        var icon = "";
        var kv = {"usercode": usercode, "k2": ""};
        if (self.page == Constant.page.JXNG || self.page == Constant.page.LHFP) {
          tdId = (self.page === Constant.page.JXNG) ? "1001" : "1002";
          title = (self.page === Constant.page.JXNG) ? "大王，精选牛股出新番啦~" : "谁敢横刀立马，唯我复盘老何";
          content = (self.page === Constant.page.JXNG) ? "速度去涨姿势" : LocalDAO.getLhfpRecommended();
          icon = "http://dl.app.gtja.com/nrng/shareimages/jxng.png";
          RemoteDAO.share(title, content, self.shareurl, "title", icon);
          TDAPP.onEvent(tdId, "", kv);
          TDAPP.send();
        } else {
          switch (self.page) {
            case Constant.storage.SHARE_SELF_DETAILS : //分享个人详情页
              title = "大王，这是" + nickname + "的全部秘密";
              content = "哟，瞧瞧~";
              tdId = "1003";
              icon = "http://dl.app.gtja.com/nrng/shareimages/wodegeren.png";
              break;
            case Constant.storage.SHARE_OTHER_DETAILS: //分享他人详情页
              title = "大王，这个牛人需要好好观察";
              content = "快领我去看看！";
              tdId = "1007";
              icon = "http://dl.app.gtja.com/nrng/shareimages/niurengeren.jpg";
              break;
            case Constant.storage.SHARE_MEDALS_WALL: //分享勋章墙
              title = "不定期出来嘚瑟一下，说不定有谁看上我呢";
              content = "我的勋章墙震撼公布";
              tdId = "1006";
              icon = "http://dl.app.gtja.com/nrng/shareimages/xunzhangqiang.png";
              break;
            case  Constant.storage.SHARE_SUBSCRIPTIONS: //分享我订阅的牛人
              title = "大王，听说这几个哥们儿挺厉害的";
              content = "赶紧认识一下";
              tdId = "1008";
              icon = "http://dl.app.gtja.com/nrng/shareimages/dingyuedeniuren.png";
              break;
            case Constant.storage.SHARE_ADMIRERS: //分享点赞我的人
              title = "哈哈哈，原来有这么多人赞我";
              content = "这些年的努力没白费";
              tdId = "1014";
              icon = "http://dl.app.gtja.com/nrng/shareimages/dianzanwoderen.png";
              break;
            case Constant.storage.SHARE_FANS: //分享我的粉丝
              title = "感谢有你，我们风雨同行";
              content = "我和粉丝们的历险记";
              tdId = "1015";
              icon = "http://dl.app.gtja.com/nrng/shareimages/wodefensi.png";
              break;
            case Constant.storage.SHARE_GAME_DETAILS: //分享比赛详情页
              title = "无兄弟，不炒股";
              content = "兄弟们在" + LocalDAO.getShareGameDetails().overview.gameName + "等你呢";
              tdId = "1011";
              icon = "http://dl.app.gtja.com/nrng/shareimages/bisaijinxing.png";
              break;
            case Constant.storage.SHARE_GAME_SELF_DETAIL: //分享我的比赛持仓页
              tdId = "1004";
              icon = "http://dl.app.gtja.com/nrng/shareimages/bisai1.png";
              break;
            case Constant.storage.SHARE_GROUP: //组合详情
              title = "报～～大王，前方发现高能组合";
              content = LocalDAO.getShareGroup().group_data.nick_name + "的组合:" + LocalDAO.getShareGroup().group_data.group_name;
              tdId = "1009";
              icon = "http://dl.app.gtja.com/nrng/shareimages/niurengeren.jpg";
              break;
            case Constant.storage.PORTFOLIO_MY_LEARN: //我偷师的组合
              title = "大王～这是您要的" + LocalDAO.getNickname() + "的偷师组合";
              content = "看看葫芦里卖的上面药去";
              tdId = "1016";
              icon = "http://dl.app.gtja.com/nrng/shareimages/toushizuhe.jpg";
              break;
            case Constant.page.STOCK_BASE_DETAIL: //炒股基础详情页
              title = "国泰君安君弘牛人牛股";
              content = "炒股基础:" + LocalDAO.getStockBaseDetail().title;
              tdId = "";
              icon = "http://dl.app.gtja.com/nrng/shareimages/niurengeren.jpg";
              break;
            case Constant.page.FUND_BASE_DETAIL: //基金基础详情页
              title = "国泰君安君弘牛人牛股";
              content = "基金基础:" + LocalDAO.getFundBaseDetail().title;
              tdId = "";
              icon = "http://dl.app.gtja.com/nrng/shareimages/niurengeren.jpg";
              break;
            default:break;
          };

          if(tdId){
            TDAPP.onEvent(tdId, "", kv);
            TDAPP.send()
          }
          RemoteDAO.sendShareData(self.page, function (data) {
            var url = "http://dl.app.gtja.com/nrng/share/" + self.page + ".html?userCode=" + usercode + "&url=" + data;
            RemoteDAO.share(title, content, url, "title", icon);
          });
        }
      }
    },
    render: function (createElement) {
      var self = this
      if (self.btn === Constant.operation.SEARCH) { // 搜索
        self.class = 'common-app-btn-search'
        self.iconclass = 'iconfont icon-sousuo'
        self.clickMethod = self.search
      } else if (self.btn === Constant.operation.SEARCH_IN_BUILD_GROUP) { // 刷新
        self.class = 'common-app-btn-search'
        self.iconclass = 'iconfont icon-sousuo'
        self.clickMethod = self.searchInBuildGroup
      } else if (self.btn === Constant.operation.REFRESH) { // 刷新
        self.class = 'common-app-btn-refresh'
        self.iconclass = 'iconfont icon-shuaxin'
        self.clickMethod = self.refresh
      } else if (self.btn === Constant.operation.SHARE) { // 分享
        self.class = 'common-app-btn-share'
        self.iconclass = 'iconfont icon-fenxiang'
        self.clickMethod = self.share
      } else if (self.btn === Constant.operation.BUILD_GROUP) { // 创建组合
        self.class = 'common-app-btn-buildGame'
        self.iconclass = 'iconfont icon-chuangjianzuhe'
        self.clickMethod = self.buildGroup
      } else if (self.btn === Constant.operation.BUILD_GAME) { // 创建比赛
        self.class = 'common-app-btn-buildGame'
        self.iconclass = 'iconfont icon-chuangjianbisai'
        self.clickMethod = self.buildGame
      } else if (self.btn === Constant.operation.HEADER) { // 头像
        self.class = 'common-app-btn-header'
        self.iconclass = 'iconfont icon-niuren'
        self.clickMethod = self.selfDetail
      } else if (self.btn === Constant.operation.GAME_RULES ) { // 比赛规则
        self.class = 'common-app-btn-gameRule'
        self.iconclass = 'iconfont icon-bisaiguize'
        self.clickMethod = self.gameRule
      } else if (self.btn == Constant.operation.HUGE_GAME_RULES) { // 车轮赛比赛规则
        self.class = 'common-app-btn-gameRule'
        self.iconclass = 'iconfont icon-bisaiguize'
        self.clickMethod = self.hugeGameRule
      } else if (self.btn == Constant.operation.JYS_GAME_RULES) { // 精英赛比赛规则
        self.class = 'common-app-btn-gameRule'
        self.iconclass = 'iconfont icon-bisaiguize'
        self.clickMethod = self.jysGameRule
      } else if (self.btn === Constant.operation.TUTORIAL) { // 新手引导
        self.class = 'common-app-btn-tutorial'
        self.iconclass = 'iconfont icon-iconfontxinshouyindao'
        self.clickMethod = self.tutorial
      } else if(self.btn === Constant.operation.QUESTION) { // 基金购买说明
        self.class = 'common-app-btn-question'
        self.iconclass = 'iconfont icon-icon-test'
        self.clickMethod = self.quest
      }
      return createElement(
        'div',
        {
          attrs: {
            class: self.class
          },
          on: {
            click: function () {
              self.clickMethod()
            }
          }
        },
        [
          createElement('i', {
            attrs: {
              class: self.iconclass
            }
          })
        ]
      )
    }
  })
</script>
